package com.example.admin.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketSessionMessage {

    // 用于存储WebSocket会话的Map
    private final Map<String, WebSocketSession> map = new ConcurrentHashMap<>();

    // 添加WebSocket会话
    public void addSession(WebSocketSession webSocketSession) {
        map.put(webSocketSession.getId(), webSocketSession);
    }

    // 移除WebSocket会话
    public void removeSession(WebSocketSession webSocketSession) {
        map.remove(webSocketSession.getId());
    }

    // 广播消息给所有打开的WebSocket会话
    public void broadcastMessage(String message) throws Exception {
        for (WebSocketSession webSocketSession : map.values()) {
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage(message));
            }
        }
    }
}
